package com.nxp.nfc_demo.updata;

import java.net.HttpURLConnection;

import org.json.JSONObject;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;

import android.app.Activity;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class VercodeUpdate implements Runnable {
    private static String TAG = "VercodeUpdate";
    private Activity mActivity = null;
    private static final String HTTP_URL = "http://api.smartfire.cn/NFC/NFC2COM/updata.json";
    private String appname = null;
    private String vername = null;
    private String vercode = null;
    private String instruction = null;
    private String apkurl = null;
    private String apkmd5 = null;
    private StringBuffer sb;
    private Boolean isGetFinish;

    // ==
    /**
     * 构造方法
     * 
     * @param mActivity
     */
    public VercodeUpdate(Activity activity, Handler handler) {
	mActivity = activity;
    }

    @Override
    public void run() {
	isGetFinish = false;
	getdate();
	try {
	    Thread.sleep(1000);
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
	if (!isGetFinish)
	    getdate();
    }

    private void getdate() {
	Log.i(TAG, "send URL");
	AQuery aq = new AQuery(mActivity);
	aq.ajax(HTTP_URL, String.class, this, "jsyhcallBack");
    }

    public void jsyhcallBack(String jsyhurl, String data, AjaxStatus status) {
	isGetFinish = true;
	Log.i(TAG, "Receive Data");
	if (status.getCode() == HttpURLConnection.HTTP_OK) {
	    String result = UnicodeUtil.decodeUnicode(data);
	    try {
		JSONObject jsonObject = new JSONObject(result);
		appname = jsonObject.getString("appname");
		vername = jsonObject.getString("verName");
		vercode = jsonObject.getString("verCode");
		instruction = jsonObject.getString("instruction");
		apkurl = jsonObject.getString("apkurl");
		apkmd5 = jsonObject.getString("apkmd5");
	    } catch (Exception e) {
		e.printStackTrace();
		Toast.makeText(mActivity, "数据不正确！", Toast.LENGTH_SHORT).show();
	    }

	    UpdateManager um = new UpdateManager(mActivity);
	    um.setAPKUrl(apkurl);
	    um.setAppName(appname);
	    um.setVersion(Integer.valueOf(vercode));
	    um.checkUpdate();

	    sb = new StringBuffer();
	    sb.append(" appname = ");
	    sb.append(appname);
	    sb.append("\r\n");
	    sb.append(" vername = ");
	    sb.append(vername);
	    sb.append("\r\n");
	    sb.append(" vercode = ");
	    sb.append(vercode);
	    sb.append("\r\n");
	    sb.append(" instruction = ");
	    sb.append(instruction);
	    sb.append("\r\n");
	    sb.append(" apkurl = ");
	    sb.append(apkurl);
	    sb.append("\r\n");
	    sb.append(" apkmd5 = ");
	    sb.append(apkmd5);
	    Log.i(TAG, sb.toString());

	} else {
	    Toast.makeText(mActivity, "获取数据失败", Toast.LENGTH_SHORT).show();
	}
    }

}